﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
using System.Data.SqlClient;
using System.Globalization;

namespace sistemaAcademicoFinanceiroEscolas
{
    public partial class InsertValorEspecialAluno : System.Web.UI.Page
    {
        protected MetaTable table;

        protected void Page_Init(object sender, EventArgs e)
        {
            DynamicDataManager1.RegisterControl(DetailsView1);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            table = DetailsDataSource.GetTable();
            Title = table.DisplayName;


            if (!Page.IsPostBack)
            {
                // Carregar alunos existentes e ativos

                SqlConnection sqlc = new SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqlc.Open();

                string sqlAluno = "select * from aluno order by nomeAluno";

                SqlCommand cmdAluno = new SqlCommand(sqlAluno, sqlc);
                SqlDataReader myReaderAluno = cmdAluno.ExecuteReader();

                ListItem AlunoSelecione = new ListItem();
                AlunoSelecione.Value = "0";
                AlunoSelecione.Text = "Selecione um Aluno";

                lstAluno.Items.Add(AlunoSelecione);

                if (myReaderAluno.HasRows)
                {

                    while (myReaderAluno.Read())
                    {
                        ListItem Aluno = new ListItem();

                        Aluno.Value = myReaderAluno["codigoAluno"].ToString();
                        Aluno.Text = myReaderAluno["nomeAluno"].ToString();

                        lstAluno.Items.Add(Aluno);
                    }

                }
                //Aluno carregados
                myReaderAluno.Close();
                cmdAluno.Dispose();

                // fechando conexão com o banco de dados
                sqlc.Close();
            }


        }

        protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            if (e.CommandName == DataControlCommands.CancelCommandName)
            {
                Response.Redirect(table.ListActionPath);
            }
        }

        protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            if (e.Exception == null || e.ExceptionHandled)
            {
                System.Data.SqlClient.SqlConnection sqlc = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqlc.Open();

                System.Data.SqlClient.SqlConnection sqld = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqld.Open();

                string sqlMax = "SELECT MAX(codigoValorEspecialAluno) AS codigoValorEspecialAluno FROM valorEspecialAluno";

                System.Data.SqlClient.SqlCommand cmdPegar = new System.Data.SqlClient.SqlCommand(sqlMax, sqlc);
                System.Data.SqlClient.SqlDataReader drPegar = cmdPegar.ExecuteReader();
                drPegar.Read();

                string codigovalorAulaMax = drPegar["codigoValorEspecialAluno"].ToString();

                cmdPegar.Dispose();
                drPegar.Close();




                cmdPegar = new SqlCommand("UPDATE valorEspecialAluno SET codigoAluno = " + lstAluno.SelectedValue + " WHERE codigoValorEspecialAluno = " + codigovalorAulaMax + "", sqlc);
                cmdPegar.ExecuteNonQuery();





                string sqlDatas = "SELECT * FROM valorEspecialAluno where codigoValorEspecialAluno = " + codigovalorAulaMax;

                System.Data.SqlClient.SqlCommand cmdPegarDatas = new System.Data.SqlClient.SqlCommand(sqlDatas, sqlc);
                System.Data.SqlClient.SqlDataReader drPegarDatas = cmdPegarDatas.ExecuteReader();
                drPegarDatas.Read();

                string dataFinal = drPegarDatas["dataFinalValorEspecialAluno"].ToString();
                string dataInicial = drPegarDatas["dataInicialValorEspecialAluno"].ToString();
                string aulaValor = drPegarDatas["valorValorEspecialAluno"].ToString();
                string codigoAluno = drPegarDatas["codigoAluno"].ToString();


                cmdPegarDatas.Dispose();
                drPegarDatas.Close();
             
                string sqlVerificarData = "SELECT * FROM valorEspecialAluno WHERE codigoAluno = "+ codigoAluno +" and codigoValorEspecialAluno <> " + codigovalorAulaMax;

                System.Data.SqlClient.SqlCommand cmdPegarVerificarData = new System.Data.SqlClient.SqlCommand(sqlVerificarData, sqlc);
                System.Data.SqlClient.SqlDataReader drPegarVerificarData = cmdPegarVerificarData.ExecuteReader();

                if (drPegarVerificarData.HasRows)
                {
                    while (drPegarVerificarData.Read())
                    {
                        string datasIniciais = drPegarVerificarData["dataInicialValorEspecialAluno"].ToString();
                        string datasFinais = drPegarVerificarData["dataFinalValorEspecialAluno"].ToString();
                        string codigoAlunos = drPegarVerificarData["codigoAluno"].ToString();

                        if (Convert.ToDateTime(dataInicial) >= Convert.ToDateTime(datasIniciais) && Convert.ToDateTime(dataInicial) <= Convert.ToDateTime(datasFinais) && codigoAluno == codigoAlunos)
                        {
                            string sqlDelDet = "delete from valorEspecialAluno where codigoValorEspecialAluno = " + codigovalorAulaMax;

                            System.Data.SqlClient.SqlCommand del = new System.Data.SqlClient.SqlCommand(sqlDelDet, sqld);
                            del.ExecuteNonQuery();
                            del.Dispose();

                            Response.Redirect("Insert.aspx?erro=jaExiste");
                        }

                        if (Convert.ToDateTime(dataFinal) >= Convert.ToDateTime(datasIniciais) && Convert.ToDateTime(dataFinal) <= Convert.ToDateTime(datasFinais) && codigoAluno == codigoAlunos)
                        {
                            string sqlDelDet = "delete from valorEspecialAluno where codigoValorEspecialAluno = " + codigovalorAulaMax;

                            System.Data.SqlClient.SqlCommand del = new System.Data.SqlClient.SqlCommand(sqlDelDet, sqld);
                            del.ExecuteNonQuery();
                            del.Dispose();

                            Response.Redirect("Insert.aspx?erro=jaExiste");
                        }
                    }  
                }
             
                
                cmdPegarVerificarData.Dispose();
                drPegarVerificarData.Close();

                DateTime Hoje = DateTime.Now;
                string dataAtual = Hoje.ToString("dd/MM/yyyy");

                if (dataFinal == "")
                {
                    dataFinal = dataAtual;
                }

                DateTime dataInicialC = DateTime.ParseExact(dataInicial, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

                DateTime dataFinalC = DateTime.ParseExact(dataFinal, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

                TimeSpan dif = Convert.ToDateTime(dataFinalC).Subtract(Convert.ToDateTime(dataInicialC));

                //Response.Write(" A subtração :  " + dif);

                //Response.End();
          
               
                if (dif.Days > 0)
                {

                    Response.Redirect(table.ListActionPath);
                } 
                else
                {
                    string sqlDelDet = "delete from valorEspecialAluno where codigoValorEspecialAluno = " + codigovalorAulaMax;

                    System.Data.SqlClient.SqlCommand del = new System.Data.SqlClient.SqlCommand(sqlDelDet, sqlc);
                    del.ExecuteNonQuery();
                    del.Dispose();

                    Response.Redirect("Insert.aspx?erro=dataMenor");
                }

                sqlc.Close();
                sqld.Close();

                Response.Redirect(table.ListActionPath);
               
            }
        }
    }
}
